//
//  CustomNewsViewController.m
//  AmountBody
//
//  Created by smm on 2018/1/8.
//  Copyright © 2018年 RCMTM. All rights reserved.
//

#import "CustomNewsViewController.h"
#import "CustomNewsView.h"
#import <AmountBody-Swift.h>
#import "CustomNewsAmountViewController.h"
#import <ReactiveObjC/ReactiveObjC.h>

@interface CustomNewsViewController ()<CAAnimationDelegate>
{
    CAShapeLayer *_maskLayer;
    CGRect _anchorRect;
}
@property (strong, nonatomic) UIImageView *backGroundImage;
//左侧图片及按钮
@property (strong, nonatomic) CustomMeasureView * measureView;
@property (strong, nonatomic) CustomNewsView * customView;
@end

@implementation CustomNewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.canScrollToNext = YES;
    [self loadUI];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    @weakify(self);
    _measureView.buttonTapsAction = ^(NSInteger index, UIView *itemView) {
        @strongify(self);
        NewsAmountType type = index + 10;
        CustomNewsAmountViewController * tmpVC = [[CustomNewsAmountViewController alloc]init];
        tmpVC.hidesBottomBarWhenPushed  = YES;
        switch (type) {
            case NewsAmountTypeForCYCC://成衣尺寸
            {
                tmpVC.amountType = NewsAmountTypeForCYCC;
                
            }
                break;
            case NewsAmountTypeForZZLT://自主量体
            {
                
                tmpVC.amountType = NewsAmountTypeForZZLT;
            }
                break;
            case NewsAmountTypeForZZXZ://自主选择
            {
                tmpVC.amountType = NewsAmountTypeForZZXZ;
                
            }
                break;
            default:
                break;
        }
        
        NSLog(@"%@", @(type));
        
        [self.parentViewController addChildViewController:tmpVC];
        [self.view.superview bringSubviewToFront:self.view];
        tmpVC.view.frame = self.view.frame;
        [self.view.superview addSubview:tmpVC.view];
        CGRect rect = [itemView.superview convertRect:itemView.frame toView:self.view];
        _anchorRect = rect;
        [self animation:self.view andToView:tmpVC.view];
        [self animationPosition:self.view andToView:tmpVC.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.transitionCompletionAction) {
                self.transitionCompletionAction(tmpVC);
            }
        });
    };
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}
#pragma mark -  按钮动画
-(void)animation:(UIView*)fromView andToView:(UIView*)toView
{
    //创建一个 CAShapeLayer 来负责展示圆形遮盖
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    //    toView.layer.mask = maskLayer;
    maskLayer.bounds = fromView.layer.bounds;
    maskLayer.position = fromView.layer.position;
    maskLayer.fillColor = toView.backgroundColor.CGColor;
    [fromView.layer addSublayer:maskLayer];
    _maskLayer = maskLayer;
    
    //开始的圆环
    UIBezierPath *startPath =  [UIBezierPath bezierPathWithOvalInRect:_anchorRect];
    //结束圆环
    CGFloat radius = [self radiusOfBubbleInView:toView startPoint:CGPointMake(CGRectGetMidX(_anchorRect), CGRectGetMidY(_anchorRect))];
    UIBezierPath *finalPath = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(_anchorRect, - radius, - radius)];
    
    //圆形放大的动画
    //将它的 path 指定为最终的 path 来避免在动画完成后会回弹
    maskLayer.path = finalPath.CGPath;
    CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    maskLayerAnimation.fromValue = (__bridge id)(startPath.CGPath);
    maskLayerAnimation.toValue = (__bridge id)((finalPath.CGPath));
    maskLayerAnimation.duration = 0.35;
    maskLayerAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    maskLayerAnimation.delegate = self;
    [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];
}
-(void)animationPosition:(UIView*)fromView andToView:(UIView*)toView
{
    //    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    
    //位移动画
    toView.layer.position = CGPointMake(CGRectGetMidX(toView.bounds), CGRectGetMidY(toView.bounds));
    CABasicAnimation *positionAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
    positionAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(CGRectGetMidX(_anchorRect), CGRectGetMidY(_anchorRect))];
    positionAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(CGRectGetMidX(toView.bounds), CGRectGetMidY(toView.bounds))];
    positionAnimation.duration = 0.35;
    positionAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [toView.layer addAnimation:positionAnimation forKey:@"position"];
    
    //缩放动画
    toView.transform = CGAffineTransformMakeScale(1, 1);
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleAnimation.fromValue = @(0);
    scaleAnimation.toValue = @(1);
    scaleAnimation.duration = 0.35;
    scaleAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [toView.layer addAnimation:scaleAnimation forKey:@"scale"];
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    //通知上下文 动画结束
    NSLog(@"动画结束");
    [self.view removeFromSuperview];
    //移除遮罩layer
    [_maskLayer removeFromSuperlayer];
    _maskLayer = nil;
}
//遍历view的四个角 获取最长的半径
-(CGFloat)radiusOfBubbleInView:(UIView*)view startPoint:(CGPoint)startPoint{
    
    //获取四个角所在的点
    CGPoint point1 = CGPointMake(0, 0);
    CGPoint point2 = CGPointMake(view.bounds.size.width, 0);
    CGPoint point3 = CGPointMake(0 ,view.bounds.size.height);
    CGPoint point4 = CGPointMake(view.bounds.size.width,view.bounds.size.height);
    NSArray *pointArrar = @[[NSValue valueWithCGPoint:point1],[NSValue valueWithCGPoint:point2],[NSValue valueWithCGPoint:point3],[NSValue valueWithCGPoint:point4]];
    //做一个冒泡排序获得最长的半径
    CGFloat radius = 0;
    for (NSValue *value in pointArrar) {
        CGPoint point = [value CGPointValue];
        CGFloat apartX = point.x - startPoint.x;
        CGFloat apartY = point.y - startPoint.y;
        CGFloat realRadius = sqrt(apartX*apartX + apartY*apartY);
        if (radius <= realRadius) {
            radius = realRadius;
        }
    }
    return radius;
}

#pragma mark -  UI布局
-(void)loadUI
{
    CGFloat jianGeH = 20;
    CGFloat top = 100; // 顶端盖高度
    CGFloat bottom = 20 ; // 底端盖高度
    CGFloat left = 80; // 左端盖宽度
    CGFloat right = 20; // 右端盖宽度
    UIImage * image = [UIImage imageNamed:@"custom_custom_info"];
    
    // 指定为拉伸模式，伸缩后重新赋值
    image = [image stretchImageWithInsetsTop:top left:left bottom:bottom right:right];
    left = 60;
    _backGroundImage = [[UIImageView alloc]init];
    [self.rightView addSubview:_backGroundImage];
    [_backGroundImage mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.rightView);
    }];
    _backGroundImage.image = image;
    _backGroundImage.userInteractionEnabled = YES;
    
    _customView = [[CustomNewsView alloc]init];//WithFrame:CGRectMake(left, top, b_imageW-left-right*2, b_imageH-top-bottom)
    [_backGroundImage addSubview:_customView];
    [_customView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_backGroundImage).offset(left);
        make.top.equalTo(_backGroundImage).offset(top);
        make.right.equalTo(_backGroundImage).offset(-right*2);
//        make.bottom.equalTo(_backGroundImage).offset(-bottom);
    }];
    [_customView loadUIForCustomNewsView];

    _measureView = [[CustomMeasureView alloc] init];
    [self.leftView addSubview: _measureView];
    
    _measureView.isEnabled = YES;
    [_measureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.leftView);
    }];
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [_backGroundImage mas_updateConstraints:^(MASConstraintMaker *make) {
        layoutViews(^{
            make.left.equalTo(self.rightView);
            make.right.equalTo(self.rightView).offset(-20);
            make.bottom.equalTo(self.rightView).offset(-30);
        }, ^{
            make.left.equalTo(self.rightView).offset(20);
            make.right.equalTo(self.rightView).offset(-20);
            make.bottom.equalTo(self.rightView).offset(-20);
        });
        
    }];
    
    [_customView mas_updateConstraints:^(MASConstraintMaker *make) {
        layoutViews(^{ //横屏
            make.top.equalTo(_backGroundImage).offset(100);
            make.bottom.equalTo(_backGroundImage).offset(-40);
            [_customView loadUIForCustomNewsViewHorizontal];
        }, ^{ //竖屏
            make.top.equalTo(_backGroundImage).offset(80);
            make.bottom.equalTo(_backGroundImage).offset(-10);
            [_customView loadUIForCustomNewsViewVertical];
            
        });
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -  暂时没有用
-(void)jieQuPhoto//截取当前View的图片
{
    if(&UIGraphicsBeginImageContextWithOptions !=NULL)
    {
        UIGraphicsBeginImageContextWithOptions(self.view.frame.size,NO,0.0);
    }
    //获取图像
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageView * imageView = [[UIImageView alloc]init];
    [self.view.superview addSubview:imageView];
    imageView.frame = CGRectMake(0, 0, 1000, 1000);
    imageView.image = image;
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
